package com.java.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.java.util.resp.BaseRespone;
import com.java.util.resp.EditorRespone;

@Controller
@RequestMapping("/file")
public class FileController {

	@Value("${file.dir}")
	String fileDir;

	@Value("${file.show}")
	String fileShow;

	@RequestMapping("/upload")
	@ResponseBody
	public BaseRespone upload(MultipartFile file) throws IOException {
		// 生成新的文件名称
		String suffix = getExtension(file.getOriginalFilename());
		String newFileName = UUID.randomUUID().toString().replace("-", "");
		File dateDir = new File(fileDir);
		if (!dateDir.exists())
			dateDir.mkdirs();
		file.transferTo(new File(dateDir, newFileName + "." + suffix));
		return new BaseRespone(0, file.getOriginalFilename(), fileShow + "/file/download/" + newFileName + "/" + suffix);
	}
	
	@PostMapping(value = "/uploadEditor")
	public EditorRespone uploadWangEditor(MultipartFile file) {
		try {
			Map<String,Object> data = new HashMap<String,Object>();
			BaseRespone resp = upload(file);
			if(resp.getStatus() == 0) {
				data.put("url", fileShow + resp.getMsg());
				data.put("name", resp.getData());
				return EditorRespone.success(data);
			}
		} catch (IOException e) {
	    	return EditorRespone.error();
		}
    	return EditorRespone.error();
	}


	@GetMapping("/download/{fileName}/{suffix}")
	public void download(@PathVariable String fileName, @PathVariable String suffix, HttpServletResponse response) throws IOException {
		// 获取打开方式
		String name = fileName + "." + suffix;
		File ff = new File(fileDir, name);
		if(ff.exists()) {
			FileInputStream is = new FileInputStream(ff);
			response.setHeader("content-disposition", "inline;fileName=" + URLEncoder.encode(name, "UTF-8"));
			ServletOutputStream os = response.getOutputStream();
			IOUtils.copy(is, os);
			IOUtils.closeQuietly(is);
			IOUtils.closeQuietly(os);
		}else {
			response.setStatus(404);
		}
	}

	public static String getExtension(String fileName) {
		return fileName.substring(fileName.lastIndexOf(".") + 1);
	}
	
	public static String encrypt(String text) {
		StringBuilder encryptedText = new StringBuilder();
		for (char c : text.toCharArray()) {
			encryptedText.append((char) (c + 1));
		}
		return encryptedText.toString();
	}
	
	public static String decrypt(String encryptedText) {
		StringBuilder text = new StringBuilder();
		for (char c : encryptedText.toCharArray()) {
			text.append((char) (c - 1));
		}
		return text.toString();
	}
}
